#! /usr/bin/env python3
import os
import sys
import cgi
import json
import subprocess
import loginWeb

_PLATFORM = "win" in sys.platform and "windows" or "linux"


def get_config(path="config.json"):
    with open(path, "r+", encoding="utf-8") as f:
        json_dict = json.load(f)
        return json_dict


def login():
    config = get_config()
    note_path = config.get("note_path", {}).get(_PLATFORM, None)
    except_list = config.get("except_list", None)
    loginWeb.main(note_path, except_list)


def get_main_html(body):
    header = "Content-type:text/html\n\n"
    with open("html/main.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        constent = constent.format(main=body, sel_part="")
        return str(header + constent)


if __name__ == "__main__":
    config = get_config()
    cgi_mod = cgi.FieldStorage()
    pass_list = config.get("passwd", None)
    states = False
    try:
        cookies = os.getenv("HTTP_COOKIE")
        exec(cookies)
        if state in pass_list:
            states = True
    except Exception:
        pass
    if states is False:
        login()
    else:
        shell = cgi_mod.getvalue('shell', "None")
        config = get_config()
        note_path = config.get("note_path", {}).get(_PLATFORM, None)
        shell = cgi_mod.getvalue('shell', "None")
        sh = ""
        button = "<a href=\"shellWeb.py?shell=pull\">PULL</a>%s<a href=\"shellWeb.py?shell=push\">PUSH</a></br>" % ("&nbsp;" * 80)
        if shell == "none":
            body = button + ""
            html = get_main_html(body)
            print(html)
        else:
            if shell == "pull":
                sh = "pull"
            elif shell == "push":
                sh = "push"
            cmd = "/bin/bash %s/shell/%s.sh" % (os.path.dirname(note_path), sh)
            popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=1)
            constent = popen.stdout.read()
            body = button + "<hr>%s" % str(constent.decode().replace("\r", "").replace("\n", "<br />"))
            html = get_main_html(body)
            print(html)
